﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Maths.Graphs
{
    public class StraightLineGraph : IGraph
    {
        private readonly string _xAxisText;
        private readonly string _yAxisText;

        private List<Point> _points = new List<Point>();

        public StraightLineGraph(string xAxisText, string yAxisText)
        {
            _xAxisText = xAxisText;
            _yAxisText = yAxisText;
        }

        public string XAxisText
        {
            get { return _xAxisText; }
        }

        public string YAxisText
        {
            get { return _yAxisText; }
        }

        public void AddPoint(double x, double y)
        {
            _points.Add(new Point(x, y));
        }

        public double GetXValue(double y)
        {
            throw new NotImplementedException();
        }

        public double GetYValue(double x)
        {
            double yValue = 0;

            List<Point> sorted = _points.OrderBy(xAxis => xAxis.X).ToList();

            for (int i = 0; i < sorted.Count; i++)
            {
                Point pointA = sorted[i];
                Point pointB = sorted[i + 1];
                if (x >= pointA.X && x <= pointB.X)
                {
                    double xOffset = pointB.X - pointA.X;
                    double yOffset = pointB.Y - pointA.Y;
                    double gradient = yOffset/xOffset;
                    double intersect = pointA.Y - (pointA.X*gradient);
                    yValue = (x*gradient) + intersect;

                    break;
                }
            }

            return yValue;
        }
    }
}
